import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入需要的路由组件
import Reg from '@/views/Reg.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'
import store from '@/store'
import Home from '@/views/Menus/Home.vue'
import UserInfo from '@/views/Menus/user/userInfo.vue'
import UserAvatar from '@/views/Menus/user/Avatar.vue'
import UserPwd from '@/views/Menus/user/Pwd.vue'
import ArtCate from '@/views/Menus/artic/List.vue'
import ArtList from '@/views/Menus/artic/ArtlList.vue'
Vue.use(VueRouter)

const router = new VueRouter({
  // 路由规则
  routes: [
    { path: '/reg', component: Reg },
    { path: '/login', component: Login },
    // 后台主页的路由规则
    {
      path: '/',
      component: Main,
      // 3. 开启路由重定向
      redirect: '/home',
      children: [
        // 子路由规则
        { path: '/home', component: Home },
        { path: '/user-info', component: UserInfo },
        { path: 'user-avatar', component: UserAvatar },
        { path: 'user-pwd', component: UserPwd },
        // 文章分类
        { path: 'art-cate', component: ArtCate },
        { path: 'art-list', component: ArtList }
      ]
    }
  ]
})

// 声明全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    // 不需要访问 直接放行
    next()
  } else {
    // 需要访问权限 判断 token
    // 技术难点 ：在js文件中怎么拿到 vuex 中的token  通过引入store 模块
    const token = store.state.user.token
    if (token) {
      // token 有值 放行
      next()
    } else {
      // token 没值 强制跳转到登录界面
      next('/login')
    }
  }
})

export default router
